package com.tjl.yangxixis.activity;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lyp.jsonbean.MAllTaskBean;
import com.lyp.jsonbean.SignBean;
import com.tjl.yangxixis.R;
import com.tjl.yangxixis.api.YangxixiApi;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 * @author Administrator
 *	签到
 */
public class SignActivity extends Activity implements OnClickListener, LocationSource, AMapLocationListener{

    private ImageView mBack;
    private AMap aMap;
    private MapView mapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private MarkerOptions markerOption;
    private TextView mArrive;
    private TextView mLeave;
    int types = -1;
    private MAllTaskBean.DataBean bean;
    private static final int BAIDU_READ_PHONE_STATE =100;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        initview();
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (Build.VERSION.SDK_INT>=23){
            showContacts();
        }else{
            init();//init为定位方法
        }
    }

    private void initview(){
        bean = (MAllTaskBean.DataBean)getIntent().getExtras().get("databean");
        mBack = (ImageView) findViewById(R.id.iv_sign_back);
        mArrive = (TextView) findViewById(R.id.arrive);
        mLeave = (TextView) findViewById(R.id.leave);
        mapView = (MapView) findViewById(R.id.map);
        mBack.setOnClickListener(this);
        mArrive.setOnClickListener(this);
        mLeave.setOnClickListener(this);
    }

    public void showContacts(){
        //这里以ACCESS_COARSE_LOCATION为例
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    BAIDU_READ_PHONE_STATE);//自定义的code
        }
        else {
            init();
        }
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                        init();
                    } else {
                        // 没有获取到权限，做特殊处理
                        Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                    }
                break;
        }
    }


    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置是否只定位一次,默认为false
            mLocationOption.setOnceLocation(true);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(10000);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
            mlocationClient.startLocation();
        }
    }
    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    /**
     * 定位成功后回调函数
     */
    public void onLocationChanged(AMapLocation amapLocation) {
        // TODO Auto-generated method stub
        if (amapLocation != null&& amapLocation.getErrorCode() == 0) {
            mListener.onLocationChanged(amapLocation);//注册定位监听
            if (types == -1) {
                LogUtils.i("tag",types);
                markerOption = new MarkerOptions().anchor(0.5f, 0.5f)
                        .position(new LatLng(amapLocation.getLatitude(),amapLocation.getLongitude())).title(amapLocation.getAddress())
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker))
                        .draggable(false);
                //请求签到或签退成功后再添加标记
                Marker marker = aMap.addMarker(markerOption);
                marker.showInfoWindow();//设置默认显示一个infowinfow
            }
            String address = amapLocation.getAddress();
                if ( types == 1) {
                    try {
                        sign(types,bean.getO_id(),address);
                        new MaterialDialog.Builder(this)
                                .title("签到成功！")
                                .content("当前到达签到的位置:"+address)
                                .positiveText("确定")
                                .canceledOnTouchOutside(false)
                                .cancelable(false)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        finish();
                                    }
                                })
                                .show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (types == 0) {
                    try {
                        sign(types,bean.getO_id(),address);
                        new MaterialDialog.Builder(this)
                                .title("签到成功！")
                                .content("离开签到的位置:"+address)
                                .positiveText("确定")
                                .canceledOnTouchOutside(false)
                                .cancelable(false)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        finish();
                                    }
                                })
                                .show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        else {
            String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
            Toast.makeText(this, "定位失败!请重新定位", Toast.LENGTH_SHORT).show();
            LogUtils.i("AmapErr",errText);
        }
    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.iv_sign_back:
                finish();
                break;
            //到达
            case R.id.arrive:
                types = 1;
                mlocationClient.startLocation();
                break;
            //离开
            case R.id.leave:
                types = 0;
                mlocationClient.startLocation();
                break;
        }
    }

    //签到
    public void sign(int type,String o_id,String check_address) throws IOException {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YangxixiApi.APP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        YangxixiApi github = retrofit.create(YangxixiApi.class);
        Call<SignBean> call = github.getSign(type,o_id,check_address);
        call.enqueue(new Callback<SignBean>() {
            @Override
            public void onResponse(Call<SignBean> call, Response<SignBean> response) {
                if (response.body().getResult()== 1 ) {
                    SignActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {


                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<SignBean> call, Throwable t) {
                ToastUtils.showShort(t.getMessage());
            }
        });
    }
}
